package com.hsd.netty.server.strategy;

import com.hsd.netty.server.common.NettyHeader;
import com.hsd.netty.server.common.NettyMessage;
import com.hsd.netty.server.dispatcher.NettyHandlerDispatcher;
import com.hsd.netty.server.enums.MessageCode;
import com.hsd.netty.server.enums.MessageType;
import com.hsd.netty.server.model.RequestObject;
import com.hsd.netty.server.utils.GsonUtils;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author s.he
 * on 2020/6/1
 */
@Component
public class RequestMessageHandler extends MessageTypeHandler {
    private static final Logger logger = LoggerFactory.getLogger(RequestMessageHandler.class);

    @Autowired
    private NettyHandlerDispatcher nettyHandlerDispatcher;



    @Override
    public NettyMessage handler(ChannelHandlerContext channelHandlerContext, NettyMessage nettyMessage) {
        String body = nettyMessage.getBody();
        RequestObject requestObject = GsonUtils.gson.fromJson(body, RequestObject.class);
        logger.info("【业务请求数据】:{}", GsonUtils.toJson(requestObject));
        String execute = nettyHandlerDispatcher.execute(requestObject);
        NettyMessage result = new NettyMessage();
        NettyHeader resultHeader = new NettyHeader();
        resultHeader.setType(MessageType.RESPONSE.getCode());
        resultHeader.setSessionId(nettyMessage.getNettyHeader().getSessionId());
        resultHeader.setRequestNumber(nettyMessage.getNettyHeader().getRequestNumber());
        if(!StringUtils.equals(execute, "ERROR")) {
          resultHeader.setStatusCode(MessageCode.SUCCESS.getCode());
        } else {
            resultHeader.setStatusCode(MessageCode.ERROR.getCode());
        }
        result.setBody(execute);
        result.setNettyHeader(resultHeader);
        logger.info("【业务响应数据】:{}", GsonUtils.toJson(execute));
        return result;
    }
}
